package com.demo.mysql.base;

import org.apache.ibatis.logging.slf4j.Slf4jImpl;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.type.JdbcType;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import java.io.IOException;

/**
 * @author hushengdong
 */
public abstract class MultipleMybatisConfig extends MultipleDataSourceConfig {

    @Autowired
    protected Environment env;

    public MultipleMybatisConfig() {
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(this.multipleDataSource());
        sqlSessionFactoryBean.setTypeAliasesPackage(this.getTypeAliasesPackage());
        sqlSessionFactoryBean.setPlugins(this.getPlugins());
        if (this.mapperLocations() != null) {
            sqlSessionFactoryBean.setMapperLocations(this.getMapperLocations(this.mapperLocations()));
        } else {
            sqlSessionFactoryBean.setMapperLocations(this.getMapperLocations());
        }

        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBean.getObject();
        sqlSessionFactory.getConfiguration().setMapUnderscoreToCamelCase(true);
        sqlSessionFactory.getConfiguration().setJdbcTypeForNull(JdbcType.NULL);
        sqlSessionFactory.getConfiguration().setLogImpl(Slf4jImpl.class);
        return sqlSessionFactory;
    }

    @Bean
    public SqlSessionTemplate sqlSession() throws Exception {
        return new SqlSessionTemplate(this.sqlSessionFactory());
    }

    protected abstract String getTypeAliasesPackage();

    protected Interceptor[] getPlugins() {
        return null;
    }

    protected Resource[] getMapperLocations() {
        return new Resource[0];
    }

    protected String mapperLocations() {
        return null;
    }

    private Resource[] getMapperLocations(String mapperLocations) {
        try {
            return (new PathMatchingResourcePatternResolver()).getResources(mapperLocations);
        } catch (IOException var3) {
            return new Resource[0];
        }
    }
}
